//
//  CourseTeacherViewController.m
//  ShowYork
//
//  Created by hxh on 2020/9/2.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "LessonTeacherViewController.h"
#import "LessonDetailViewController.h"
#import "LessonCommonTitleHeaderView.h"
#import "LessonTeacherHeaderCell.h"
#import "LessonClassItemCell.h"
#import "LessonPlanModel.h"
#import "LessonTeacherModel.h"
#import "LessonSubjectItemModel.h"
@interface LessonTeacherViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,LessonClassItemCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;
@property (nonatomic,strong)UIView *navView;
@property (nonatomic,strong)UIButton *shareBtn;
@property (nonatomic,strong)UIButton *backBtn;
@property (nonatomic,strong)UIImageView *headerImgView;
@property (nonatomic,strong)UILabel *nameLb;
@property (nonatomic,copy)NSArray *dataArray;
@property (nonatomic,copy)NSArray *subjectArray;
@property (nonatomic,strong)LessonTeacherModel *teacherModel;
@end

@implementation LessonTeacherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isHideNavBar = YES;
    // 判断有没有网络
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"老师详情" completeBlock:^{
            @zf_strongify(self)
            [self setUI];
            [self loadNetwork];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self setUI];
        [self loadNetwork];
    }
    [self registNote];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[LessonTeacherHeaderCell class] forCellWithReuseIdentifier:@"LessonTeacherHeaderCell"];
    [self.collectionView registerClass:[LessonClassItemCell class] forCellWithReuseIdentifier:@"LessonClassItemCell"];
    [self.collectionView registerClass:[LessonCommonTitleHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LessonCommonTitleHeaderView"];
    [self.view addSubview:self.collectionView];

    if (@available(iOS 11.0,*)) {
           self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
       }else{
           self.automaticallyAdjustsScrollViewInsets = NO;
       }
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        }else{
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
        }
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom);
     }];
    
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.cl_height = 138.0f;
    self.collectionView.mj_footer = footer;
    
    [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    
    
//    self.collectionView.mj_footer.hidden = YES;
    
    
    self.navView = [[UIView alloc]init];
    self.navView.backgroundColor = [UIColor whiteColor];
    self.navView.alpha = 0;
    [self.view addSubview:self.navView];
        
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11,*)) {
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
        }else{
      
            make.right.equalTo(self.view.mas_right);
            make.left.equalTo(self.view.mas_left);
        }
        make.top.equalTo(self.view.mas_top);
        make.height.mas_equalTo(kNavBarHeight);
    }];
        
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_normal_tag"] forState:UIControlStateNormal];
    [self.backBtn setImage:[UIImage imageNamed:@"common_back_tag"] forState:UIControlStateSelected];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
        
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navView).offset(16);
        make.bottom.equalTo(self.navView).offset(-8);
    //        make.width.mas_equalTo(50);
    }];
        
    self.shareBtn = [[UIButton alloc]init];
    [self.shareBtn setImage:[UIImage imageNamed:@"home_detail_head_share_tag"] forState:UIControlStateNormal];
    [self.shareBtn setImage:[UIImage imageNamed:@"campus_share_tag"] forState:UIControlStateSelected];
    [self.shareBtn addTarget:self action:@selector(shareMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.shareBtn];
            
    [self.shareBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.navView).offset(-16);
        make.bottom.equalTo(self.navView).offset(-8);
        //        make.width.mas_equalTo(50);
    }];
    
    UIView *line = [[UIView alloc]init];
    line.backgroundColor = [UIColor lightGrayColor];
    [self.navView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.navView);
        make.height.mas_equalTo(0.5);
    }];
    
    self.headerImgView = [[UIImageView alloc]init];
    self.headerImgView.layer.cornerRadius = 17;
    self.headerImgView.layer.masksToBounds = YES;
    self.headerImgView.hidden = YES;
    [self.navView addSubview:self.headerImgView];
    [self.headerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.navView).offset(-25);
        make.centerY.equalTo(self.backBtn);
        make.size.mas_equalTo(CGSizeMake(34, 34));
    }];
    
    self.nameLb = [[UILabel alloc]init];
    self.nameLb.text = @"xxx";
    self.nameLb.textColor = C35;
    self.nameLb.font = [UIFont boldSystemFontOfSize:18];
    self.nameLb.hidden = YES;
    [self.navView addSubview:self.nameLb];
    
    [self.nameLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.headerImgView);
        make.left.mas_equalTo(self.headerImgView.mas_right).offset(8);
    }];
    
    self.shareBtn.hidden = YES;
}

- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)shareMethod{
    
}
#pragma mark - 注册通知
- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNetwork) name:@"updateUserInfoSource" object:nil];
}

#pragma mark - 请求网络
- (void)loadNetwork{
    
    [self showDataLoadState];
      dispatch_group_t group = dispatch_group_create();
      dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          [self loadTeacherDetail];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadAllSubjectSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadSubjectListSource];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self hideDataLoadLoadState];
        
        self.teacherModel.lessonCount = @(self.dataArray.count);
        
        if (self.dataArray.count > 0) {
           
            LessonPageItemModel *itemModel = [self.dataArray firstObject];
            
            self.teacherModel.subjectId = itemModel.subjectId;
            
            [self.headerImgView sd_setImageWithURL:[NSURL URLWithString:self.teacherModel.head]];
            
             self.nameLb.text = self.teacherModel.name;
            
        }
        [self.collectionView reloadData];
    });

}
- (void)loadTeacherDetail{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:TeacherDetail];
    param[@"id"] = self.tearcherId;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(TeacherDetail) parames:param success:^(id responseObj) {
        dispatch_semaphore_signal(sema);
        self.teacherModel = [LessonTeacherModel mj_objectWithKeyValues:responseObj[RESPONSE]];
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
     dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadAllSubjectSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTeacherAllLessons];
    param[@"id"] = self.tearcherId;
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetTeacherAllLessons) parames:param success:^(id responseObj) {
        self.dataArray = [LessonPageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
         dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}


- (void)loadSubjectListSource{
    
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SubjectList) parames:nil success:^(id responseObj) {
        self.subjectArray = [LessonSubjectItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
       dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//
}

#pragma mark - collectionViewDelegate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (self.teacherModel == nil) {
        return 0;
    }
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 1) {
        return self.dataArray.count;
    }
    return 1;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        LessonClassItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonClassItemCell" forIndexPath:indexPath];
        cell.model = self.dataArray[indexPath.row];
        cell.delegate = self;
        return cell;
    }
    LessonTeacherHeaderCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LessonTeacherHeaderCell" forIndexPath:indexPath];
    [cell setTeacherModel:self.teacherModel];
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        LessonCommonTitleHeaderView *cell = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LessonCommonTitleHeaderView" forIndexPath:indexPath];
        return cell;
    }
    return nil;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 1) {
        return UIEdgeInsetsMake(16,16, 16,16);
    }
    return UIEdgeInsetsZero;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    if (section == 1) {
        return 8.0f;
    }
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 16.0f;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return CGSizeMake(kScreenW, 54);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        LessonPageItemModel *model = self.dataArray[indexPath.item];
        return model.itemSize;
    }
    return CGSizeMake(kScreenW, kScreenW/4*3 + 50);
}

#pragma mark - CourseClassItemCellDelegate
- (void)addCoursePlanAtCurrentModel:(LessonPageItemModel *)model{
    
    [MobClick event:@"teacher_add_plan"];
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"lessonId"] = model.id;
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:AddUserPlanList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(AddUserPlanList) parames:param success:^(id responseObj) {
     
        NSMutableArray *arr = [[RPAppManager getOwnerPlanIds] mutableCopy];
        [arr addObject:model.id];
        [RPAppManager saveUserPlanIdsWithPlans:arr];
        
        NSInteger index = [self.dataArray indexOfObject:model];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"已加入学习计划" duration:2 finishHandler:nil];
    
    } failure:^(NSError *error) {
        [WHToast showImage:[UIImage imageNamed:@"toast_tag_error"] message:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}
- (void)showCourseDetailWithCurrentModel:(LessonPageItemModel *)model{
    LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
    dtlVC.lessonId = model.id;
    [self.navigationController pushViewController:dtlVC animated:YES];
    [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"teacher_detail_lesson"}];
    [MobClick event:@"teacher_show_detail_click"];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y <= 0) {
        scrollView.contentOffset = CGPointMake(0, 0);
        self.navView.alpha = 0;
        self.backBtn.selected = NO;
        self.shareBtn.selected = NO;
    }else{
        CGFloat alpha = (scrollView.contentOffset.y+kNavBarHeight)/(kScreenW/4*3 + 50);
        self.navView.alpha = alpha;
        
        if (alpha >= 1) {
            self.headerImgView.hidden = NO;
            self.nameLb.hidden = NO;
            self.backBtn.selected = YES;
            self.shareBtn.selected = YES;
        }
        self.headerImgView.hidden = alpha < 1;
        self.nameLb.hidden = alpha < 1;
    }
   
}
@end
